/*******************************************************************************
 *            SHOPPING CART COLLECTIONS CLASS EXTENDS COLLECTION CLASS
 ******************************************************************************/
function CartCollection() {};
//inherit from Collection class
CartCollection.prototype = new Collection();
//reset the contructor after inheritance
CartCollection.prototype.constructor = CartCollection;

//augmenting the prototype

//overwriting the inherited add function
CartCollection.prototype.add = function(key,value) {
    var self = this;
    if( typeof self.list[key] == 'undefined' ) {
        self.list[key] = {qty:1,data:value};
        self.size++;
    }
    else{
        var curr_qty = parseInt(self.list[key].qty);
        self.list[key].qty = curr_qty + 1;
    }
    self.fireCallbacks('add', key, value);
}

CartCollection.prototype.edit = function(key,value) {
    var self = this;
    for(var key_item in value){
        self.list[key].data[key_item] = value[key_item];
    }
    self.fireCallbacks('add', key, value);
}

//overwriting the inherited remove function
CartCollection.prototype.remove = function(key) {
    var self = this;
    if( typeof self.list[key] != 'undefined' ) {
        var curr_qty = parseInt(self.list[key].qty);
        self.list[key].qty = curr_qty - 1;
        var value = self.list[key];
        if(self.list[key].qty == 0){
            delete self.list[key];
            self.size--;
        }
        self.fireCallbacks('remove',key, value);
    }
}

//Create Data for SaleItem Model
CartCollection.prototype.createSaleItemModelData = function(interest_amt) {
    var self = this;
    var data = [];
    self.iterate(function(key,obj){
        var id = key
        var orignal_currency = obj.data.currency;
        var currency = obj.data.currency;
        var name = obj.data.name;
        var original_unit_price  = parseFloat(obj.data.amount);
        var amount = parseFloat(obj.data.amount);
        var quantity = obj.qty;

        var original_insurance_currency = obj.data.insurance_currency;
        var insurance_currency = obj.data.insurance_currency;
        var insurance_default_cost = obj.data.insurance_default_cost;
        var insurance_amt = parseFloat(obj.data.insurance_amt);
        var insurance_period = obj.data.insurance_period
        var insurance_period_yrs = obj.data.insurance_period_yrs
        var insurance_period_mth = obj.data.insurance_period_mth

        var insure = Sales.getItemInsuranceCost(id);
        insurance_currency = insure.insurance_currency;
        var insurance_cost = insure.insurance_total;

        if(currency == Sales.transaction_currency){

        }
        else{
            if(Sales.transaction_currency == '$' && currency == 'GHc'){//Covert to dollar
                amount = amount / Sales.usd_rate;
            }
            else if(Sales.transaction_currency == 'GHc' && currency == '$'){//Convert to Cedi
                amount = amount * Sales.usd_rate;
            }
            currency = Sales.transaction_currency;
        }

		data.push({
            item_id:id,
            unit_price:amount,
            interest:interest_amt,
            quantity:quantity,
            insurance_default_cost:insurance_default_cost,
            insurance_cost: insurance_cost,
            insurance_period_yrs:insurance_period_yrs,
            insurance_period_mth:insurance_period_mth,
            original_insurance_currency:original_insurance_currency,
            orignal_currency:orignal_currency,
            currency:currency,
            original_unit_price:original_unit_price,
            usd_rate:Sales.usd_rate
        });
    });

    return data;
}


CartCollection.prototype.getTotalItems = function() {
    var self = this;
    var grand_total = 0
    self.iterate(function(key,obj){
        var quantity = obj.qty;
        grand_total = grand_total + quantity;
    });
    return grand_total;
}

CartCollection.prototype.getTotalCost = function() {
    var self = this;
    var grand_total = 0.00
    self.iterate(function(key,obj){
        var currency = obj.data.currency;
        var unit_price = parseFloat(obj.data.amount);
        var quantity = obj.qty;

        if(currency == Sales.transaction_currency){

        }
        else{
            if(Sales.transaction_currency == '$' && currency == 'GHc'){//Covert to dollar
                unit_price = unit_price / Sales.usd_rate;
            }
            else if(Sales.transaction_currency == 'GHc' && currency == '$'){//Convert to Cedi
                unit_price = unit_price * Sales.usd_rate;
            }
            currency = Sales.transaction_currency;
        }

        var cost_price = unit_price * quantity; // Redo
        //var cost_price = unit_price; //Mek Change
        grand_total = grand_total + cost_price;

    });
    return grand_total;
}

CartCollection.prototype.getInsuranceTotal = function() {
    var self = this;
    var grand_total = 0.00
    self.iterate(function(key,obj){
        var insurance_currency = obj.data.insurance_currency;

        var insure = Sales.getItemInsuranceCost(key);
        insurance_currency = insure.insurance_currency;
        var insurance_cost = insure.insurance_total;
        //console.log(insurance_cost)
        grand_total = grand_total + parseFloat(insurance_cost);
    });
    //console.log(grand_total);
    return grand_total;
}


CartCollection.prototype.getDiscountAmount = function(discount,interest) {
    var self = this;
    //var grand_total = self.getTotalCostPlusInterest(interest);
    var grand_total = self.getTotalCost();
    //Update the total cost factoring in the discount
    discount = parseFloat(discount);
    if(typeof discount == "undefined" && discount.length < 1){
        discount = 0;
    }
    var deduct = (discount/100) * grand_total;

    return deduct;
}

//Get Total Cost Factoring in Discount
CartCollection.prototype.getTotalCostAfterDiscount = function(discount,interest) {
    var self = this;
   // var grand_total = self.getTotalCostPlusInterest(interest);
    var grand_total = self.getTotalCost();
    //Update the total cost factoring in the discount
    var deduct = self.getDiscountAmount(discount,interest);
    var balance = grand_total - deduct;

    return balance;
}

//Get Interest Amount
CartCollection.prototype.getInterestAmount = function(value) {
    var self = this;

    value = parseFloat(value);
    var principal = self.getTotalCost();
    var int_amt = (value/100) * principal;

    return int_amt;
}

CartCollection.prototype.getTotalCostPlusInterest = function(value) {
    var self = this;
    value = parseFloat(value);
    var int_amt = self.getInterestAmount(value);
    var principal = self.getTotalCost();
    var rt = principal + int_amt;

    return rt;
}



/*******************************************************************************
 *            END OF SHOPPING CART COLLECTIONS CLASS
 ******************************************************************************/


/*
 * @name administration.js
 * @author : Amissah Gideon<kuulmek@yahoo.com>
 */
var Sales = {

    _cart: new CartCollection(),
    transaction_currency: null,
    proforma_id:null,
    usd_rate: null,

    /* Function init
     * @param void
     * @return void
     * @access public
     * */
    init:function () {
        var self = this;

        self.transaction_currency = $('#gbl_currency').val();
        self.usd_rate = parseFloat($('#conversion_rate').val());
        $("#form  #currency").val(self.transaction_currency );

        $('#gbl_currency').change(function(){
            self.transaction_currency = $('#gbl_currency').val();
            self.usd_rate = parseFloat($('#conversion_rate').val());
            $("#form  #currency").val(self.transaction_currency );
            self.refreshCartUI();
        });

        $('#conversion_rate').focusout(function () {
            self.transaction_currency = $('#gbl_currency').val();
            self.usd_rate = parseFloat($('#conversion_rate').val());
            $("#form  #currency").val(self.transaction_currency );
            self.refreshCartUI();
        });
		
		$('#purchase_type').change(function(){
            var v = $(this).val();
            if(v == 'Non Interest Payment')
            $("#form  #interest").val('0.00');
        });

        self._cart.registerCallback('add', function(key, obj) {
            self.refreshCartUI();
        });

        self._cart.registerCallback('remove', function(key) {
            self.refreshCartUI();
        });

        Calendar.setup({
            inputField : "purchased_date",
            trigger    : "purchased_date_btn",
            onSelect   : function() { this.hide() },
            dateFormat: "%Y-%m-%d",
            showTime: false,
            animation: true
        });

        /*Add and Remove from cart*/
        $('#add-to-cart-btn').click(function () {
            self.updateInsurance();
            self.updateCart('add');
        });
        $('#remove-from-cart-btn').click(function () {
            //self.updateInsurance();
            self.updateCart('remove');
        });
        /***********************************/

        $('#form #discount').focusout(function () {
            self.refreshCartUI();
        });


        $('#form #deposit').focusout(function () {
            self.creditCheck();
        });
        $('#form #deposit_currency').change(function () {
            self.creditCheck();
        });


        $('#form #interest').focusout(function () {
            self.creditCheck();
        });
        $('#form #tenor').change(function () {
            self.creditCheck();
        });


        $('#save-btn').click(function () {
            self.saveSale();
        });

        $('#cancel-btn').click(function () {
            document.getElementById('form').reset();
            self._cart.clear();
            $("#cart ul").html('');
            self.creditCheck();
            $.validationEngine.closePrompt('.formError', true);
        });

        $("#form").validationEngine();

        /*$('#update_insurance_btn').click(function () {
            self.updateInsurance();
        });*/

        $('#recalc-btn').click(function () {
            self.updateInsurance();
        });


        //numbers only
        $('#cart ul li a input.raw_item_cost_txt, #cart ul li a input.insurance_total_txt').live('keydown',function(event) {

           /* var customRule = rules[position+1];
            var pattern = eval($.validationEngine.settings.allrules[customRule].regex);

            if(!pattern.test($(caller).attr('value'))){
                $.validationEngine.isError = true;
                promptText += $.validationEngine.settings.allrules[customRule].alertText+"<br />";
            }*/


            if(event.which == 8 || event.which == 37 || event.which == 40 || event.which == 38 || event.which == 39){
                //allow keys for backspace, arrow keys
            }
            else{
                if ((event.which != 190 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
                    console.log('prevent')
                    event.preventDefault();
                }
            }
        });

        //Load cart using proforma
        $('#load-cart-from-proforma-btn').click(function(){
            $('#cancel-btn').click();
            var title = "Please the proforma number";
            Search.search(title,$('#search-proforma-url').val(),function(modal,response){
                modal.closeModal();
                var Proforma = response.data.Proforma;
                var ProformaItem = response.data.ProformaItem;
                self.proforma_id = Proforma.id;
                $('#form #customer_id').val(Proforma.customer_id);
                $('#form #customer_id').change();
                $('#proforma_number-text').html("Proforma Loaded : "+Proforma.proforma_number);
                $('#select_items option').each(function () {
                    var id = parseInt($(this).val());
                    for (var x in ProformaItem) {
                        var y = parseInt(ProformaItem[x].item_id);
                        if (id == y) {
                            var qty = parseInt(ProformaItem[x].quantity);
                            $(this).attr('selected', 'selected');
                            $('#select_items').change();
                            for(var k = 1; k <= qty; k++){
                                $('#add-to-cart-btn').click();
                            }
                            //$(this).attr('selected', false);
                            //$('#select_items').change();
                        }
                    }
                });
                //console.log(response);
            })
        });
    },

    getItemInsuranceCost:function(item_id){
        var self = this;

        var item = self._cart.get(item_id);
        var quantity = item.qty;
        var name = item.data.name;
        var unit_price = parseFloat(item.data.amount);
        var insurance_currency = item.data.insurance_currency;
        //var insurance_default_cost = item.data.insurance_default_cost;
        var insurance_amt = item.data.insurance_amt;
        var insurance_period = parseInt(item.data.insurance_period);
        var insurance_period_mth = parseInt(item.data.insurance_period_mth);

        /*** Insurance total per item ***/
        if(insurance_currency == self.transaction_currency){}
        else{
            if(self.transaction_currency == '$' && insurance_currency == 'GHc'){//Covert to dollar
                insurance_amt = insurance_amt / self.usd_rate;
            }
            else if(self.transaction_currency == 'GHc' && insurance_currency == '$'){//Convert to Cedi
                insurance_amt = insurance_amt * self.usd_rate;
            }
            insurance_currency = self.transaction_currency;
        }
        /* total insurance for this item */

        //Temporal, don't multiply the insurance by the period and quantity, we need this for the old data capturing only, after that reverse the process
        //var insurance_cost = insurance_amt * quantity;
        //var insurance_total = insurance_cost * insurance_period;

        var insure_cost = insurance_amt //this is the default cost per year for insurance
        var insure_cost_per_mth = (parseFloat(insure_cost))/12; //get the monthly cost
        var insure_yr_to_mth = insurance_period * 12; //convert the insurance year to month
        var insure_tl_mth = insure_yr_to_mth + insurance_period_mth;
        var insurance_total = (insure_tl_mth * insure_cost_per_mth) * quantity;

        //var insurance_total = insurance_amt;
        var rt = {insurance_cost:insure_cost,insurance_total:insurance_total,insurance_currency:insurance_currency};
        return rt;
    },

    updateInsurance:function(){
        var self = this;
        $("#cart ul li a").each(function(){
            var raw_item_cost = $(this).find("input.raw_item_cost_txt");
            var raw_cost = raw_item_cost.val();

            var in_period = $(this).find("input.insurance_period_txt");
            var item_id = in_period.attr('data-id');
            var period_value = in_period.val();

            var in_period_mth = $(this).find("input.insurance_period_mth_txt");
            var period_mth_value = in_period_mth.val();

            var in_cost = $(this).find("div input.insurance_total_txt");
            var cost_value = in_cost.val();

            self._cart.edit(item_id,{
                amount:raw_cost,// comment out after data entries;
                insurance_amt:cost_value,// comment out after data entries;
                //insurance_default_cost:cost_value,
                insurance_period:period_value,
                insurance_period_yrs:period_value,
                insurance_period_mth:period_mth_value
            });
        });
        self.refreshCartUI();
        //self.creditCheck();
    },

    updateCart:function (action) {
        var self = this;

        var ids = $("#select_items").val();
        //console.log(ids);
        if(!ids){
            return false;
        }
        if (action == 'add') {
            for(var i in ids){
                var id = ids[i];
                var name = global_item_data[id]['name'];
                var currency = global_item_data[id]['currency'];
                var amount = global_item_data[id]['amount'];
                var insurance_amt = global_item_data[id]['insurance_amt'];
                var insurance_currency = global_item_data[id]['insurance_currency'];
                var insurance_period_yrs = 1;
                var insurance_period_mth = 0
                var insurance_period = 1;
                var insurance_cost = ((insurance_period_yrs * 12) + insurance_period_mth) * ((insurance_amt/12)); // This only happens once, when the item is first added to the cart, after that it will not calculate again

                if(!amount){
                    amount = 0.00;
                }
                //var interest = global_item_data[id]['interest'];
                //self._cart.add(id,{id:id,name:name,currency:currency,amount:amount,interest:interest});
                self._cart.add(id,{
                    id:id,
                    name:name,
                    currency:currency,
                    amount:amount,
                    insurance_default_cost:insurance_amt,
                    insurance_amt:insurance_cost,
                    insurance_currency:insurance_currency,
                    insurance_period:insurance_period,
                    insurance_period_yrs:insurance_period_yrs,
                    insurance_period_mth:insurance_period_mth
                });
            }
        }
        else{
            for(var i in ids){
                var id = ids[i];
                self._cart.remove(id);
            }
        }
    },

    refreshCartUI:function(){
        var self = this;

        $("#cart ul").html('');
        self._cart.iterate(function(key, obj){
            var id = key
            var name = obj.data.name;
            var currency = obj.data.currency
            var unit_price = parseFloat(obj.data.amount);
            var insurance_currency = obj.data.insurance_currency;
            var insurance_amt = obj.data.insurance_amt;
            var insurance_period = obj.data.insurance_period;
            var insurance_period_mth = obj.data.insurance_period_mth;

            if(currency == self.transaction_currency){

            }
            else{
                if(self.transaction_currency == '$' && currency == 'GHc'){//Covert to dollar
                    unit_price = unit_price / self.usd_rate;
                }
                else if(self.transaction_currency == 'GHc' && currency == '$'){//Convert to Cedi
                    unit_price = unit_price * self.usd_rate;
                }
                currency = self.transaction_currency;
            }
           /* var interest = parseFloat(obj.data.interest);*/
            var quantity = obj.qty;
            var cost_price = unit_price * quantity;//Mek Change
            //var cost_price = unit_price;//Mek Change

            /*** Insurance total per item ***/
            var insure = self.getItemInsuranceCost(id);
            insurance_currency = insure.insurance_currency;
            var insurance_cost = insure.insurance_cost;
            var insurance_total = insure.insurance_total;

            var li = $("<li />").attr('data-id',key);
            li.append($("<a />").addClass('list-link icon-inbox').attr("href","javascript:void(0);")
                .append($("<strong />").html(name+" &nbsp;"))
                .append($("<span />").addClass('qty').html('Qty x'+quantity+" &nbsp; <br />"))
                //.append($("<span />").addClass('subT').html(currency+' '+jLib.formatNumber(cost_price,'money')+" <br />"))
                .append("Unit Cost "+currency+" <input type='text' size='8' data-id='"+key+"' class='raw_item_cost_txt' value='"+jLib.formatNumber(unit_price)+"' /> Total: <span class='raw_item_cost_lbl'>"+jLib.formatNumber(cost_price)+"</span> <br />")
                //.append($("<span />").addClass('qty').html('Insurance Total :'+insurance_currency+' '+jLib.formatNumber(insurance_total,'money')+" &nbsp; <br />"))
                .append($("<div />").attr('style',"margin:7px 0px;").addClass('qty').html("Insurance:"+insurance_currency+"  <input type='text' size='8' data-id='"+key+"' class='insurance_total_txt' value='"+jLib.formatNumber(insurance_cost)+"' /> Total: <span class='insurance_total_lbl'>"+jLib.formatNumber(insurance_total)+"</span>&nbsp; <br />"))
                .append("Insurance Period <input type='text' size='2' data-id='"+key+"' class='insurance_period_txt' value='"+insurance_period+"' /> yrs")
                .append(" <input type='text' size='2' data-id='"+key+"' class='insurance_period_mth_txt' value='"+insurance_period_mth+"' /> mth <br />")
                //.append($("<div />").attr('style',"margin:7px 0px;").html("<button type='button' data-id='"+key+"' class='button compact'> Add Vehicle Numbers</button> <br />"))
            )
            $("#cart ul").append(li);
        });

        //Update the items count
        var count = self._cart.getTotalItems();
        $('#cart-count').html(count);

        var grand_total = self._cart.getTotalCost();
        $("#form #cost").val(jLib.formatNumber(grand_total,'money'));

        self.creditCheck();

        $rate =  jLib.getRate($('#form #interest').val(), $("#form #tenor").val(), $("#form #interest_rate_decimal_places").val());
        //Decimal Places for interest Ratio
        console.log($rate);
        console.log($rate * 100);

        $("#interest_rate_decimal_place_txt").find('span b').html($rate * 100);

    },


    creditCheck:function(){
        var self = this;

        var trans_currency = self.transaction_currency;
        var discount = parseFloat($("#form #discount").val());
        var tenor = parseFloat($("#form #tenor").val());
        var interest = parseFloat($("#form #interest").val()) * tenor;
        var deposit_currency = $('#form #deposit_currency').val();
        var deposit = parseFloat( $('#deposit').val()).toFixed(2);
        if(!deposit){
            deposit = 0.00;
        }
        deposit = self.getDeposit(deposit_currency,deposit);
        var deposit_format = jLib.formatNumber(deposit,'money');

        $("#deposit_conversion_rate_txt").find('span b').html(''+trans_currency+' '+deposit_format);
        if(deposit_currency == self.transaction_currency){
            $("#deposit_conversion_rate_txt").hide();
        }
        else{
            $("#deposit_conversion_rate_txt").show();
        }

        var balance = self._cart.getTotalCostAfterDiscount(discount,interest) - deposit;
        var opening_bal_plus_insurance = balance + self._cart.getInsuranceTotal();

        var amortize = jLib.get_amortization(trans_currency,opening_bal_plus_insurance,$('#form #duration_in_month').val(), $("#form #interest").val(),$("#form #tenor").val(),$("#form #interest_rate_decimal_places").val(),$('#form #purchase_type').val());
        //console.log(amortize);

        $("#items_purchased_txt").find('span b').html(''+trans_currency+' '+jLib.formatNumber(self._cart.getTotalCost(),'money'));
       // $("table tr#interest_txt").find('td span b').html(self._cart.getInterestAmount(interest).toFixed(2));
        //var tlprincipal = self._cart.getTotalCost() + self._cart.getInterestAmount(interest);
        var tlprincipal = self._cart.getTotalCost();
        $("#priciple_txt").find('span b').html(''+trans_currency+' '+jLib.formatNumber(tlprincipal,'money'));
        $("#discount_txt").find('span b').html(''+trans_currency+' '+jLib.formatNumber(self._cart.getDiscountAmount(discount,interest),'money'));
        $("#costafter_discount_txt").find('span b').html(''+trans_currency+' '+jLib.formatNumber(self._cart.getTotalCostAfterDiscount(discount,interest),'money'));
        $("#deposit_txt").find('span b').html(''+trans_currency+' '+deposit_format);
        $("#insurance_txt").find('span b').html(''+trans_currency+' '+jLib.formatNumber(self._cart.getInsuranceTotal(),'money'));
        $("#total_interest_txt").find('span b').html(''+trans_currency+' '+amortize.tl_inerest);
        $("#balance_txt").find('span b').html(''+trans_currency+' '+jLib.formatNumber(balance,'money'));
        $("#monthly_inst_txt").find('span b').html(''+trans_currency+' '+amortize.monthly_inst);
        $("#opening_balance_txt").find('span b').html(''+trans_currency+' '+jLib.formatNumber(opening_bal_plus_insurance,'money'));
    },

    getDeposit:function(deposit_currency,deposit_value){
        var self = this;

        if(deposit_currency == self.transaction_currency){

        }
        else{
            if(self.transaction_currency == '$' && deposit_currency == 'GHc'){//Covert to dollar
                deposit_value = deposit_value / self.usd_rate;
            }
            else if(self.transaction_currency == 'GHc' && deposit_currency == '$'){//Convert to Cedi
                deposit_value = deposit_value * self.usd_rate;
            }

        }
        return deposit_value
    },


    saveSale:function () {
        var self = this;

        /* Validate the form*/
        var validationStatus = $('#form').validationEngine({returnIsValid:true});
        /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
        if (validationStatus) {

            var total_cost = self._cart.getTotalCost();
            if(total_cost == 0){
                jLib.serverError("There are no items to purchase.", 'error_message', false);
                return false;
            }

            jLib.showFormLoading();

            var deposit = parseFloat( $('#form #deposit').val());
            var discount = parseFloat($("#form #discount").val());
            var tenor = parseFloat($("#form #tenor").val());
            var interest = parseFloat($("#form #interest").val()) * tenor;
            if(!deposit){
                deposit = 0.00;
            }

            //var tlprincipal = self._cart.getTotalCost() + self._cart.getInterestAmount(interest);
            var tlprincipal = self._cart.getTotalCost();

            /*$("table tr#discount_txt").find('td span b').html(self._cart.getDiscountAmount(discount,interest).toFixed(2));
            $("table tr#costafter_discount_txt").find('td span b').html(self._cart.getTotalCostAfterDiscount(discount,interest).toFixed(2));
            $("table tr#deposit_txt").find('td span b').html(deposit);
            $("table tr#opening_balance_txt").find('td span b').html();*/
            var deposit2 = self.getDeposit($('#form #deposit_currency').val(),deposit);
            var opening_bal = (self._cart.getTotalCostAfterDiscount(discount,interest) - deposit2) + self._cart.getInsuranceTotal();
            var balance_plus_insurance = self._cart.getTotalCostAfterDiscount(discount,interest) + self._cart.getInsuranceTotal();
            var full_or_credit = 'credit';

           // console.log();
            //console.log(typeof opening_bal);
            //return;
            if(opening_bal.toFixed(2) <= 0.00){ //this is an outright payment without interest; where the deposite amount was used to clear all the opening balance
                opening_bal = balance_plus_insurance; //We still have to record the opening balance, set the deposite amount to zero, and make one repaymnet with the full amount.
                full_or_credit = 'full';
            }

            var data = {
                'Sale':{
                        full_or_credit:full_or_credit,
						officer_incharge: $('#form #officer_incharge').val(),
                        customer_id:$('#form #customer_id').val(),
                        proforma_id:self.proforma_id,
						purchase_type:$('#form #purchase_type').val(),
                        currency:$("#form  #currency").val(),
                        cost: self._cart.getTotalCost().toFixed(2),
                        discount:$('#form #discount').val(),
                        discount_amount: self._cart.getDiscountAmount(discount,interest).toFixed(2),
                        purchased_date:$('#form #purchased_date').val(),
                        deposit_currency: $('#form #deposit_currency').val(),
                        original_deposit_amt:deposit,
                        deposit:deposit2,
                        usd_rate:self.usd_rate,
                        principal: tlprincipal.toFixed(2),
                        tenor:$("#form #tenor").val(),
                        interest:$("#form #interest").val(),
                        interest_rate_decimal_places:$("#form #interest_rate_decimal_places").val(),
                        interest_amount: self._cart.getInterestAmount(interest).toFixed(2),
                        duration_in_month: $('#form #duration_in_month').val(),
                        payment_type: $('#form #payment_type').val(),
						cheque_no: $("#form #cheque_no").val(),
                        insurance_total: self._cart.getInsuranceTotal(),
                        opening_bal:opening_bal.toFixed(2),
                        tax:$('#form #tax').val(),
                        end_date:$('#form #end_date').val(),
                        comments:$('#form #comments').val()
                },
                'SaleItem':self._cart.createSaleItemModelData(self._cart.getInterestAmount(interest).toFixed(2))
            };

            var url = $('#add-edit-url').val();
            var query = 'model=Sale&data=' + encodeURIComponent(JSON.stringify(data));

            $.ajax({
                url:url,
                data:query,
                dataType:'json',
                type:'POST',
                success:function (response) {
                    var txt = '';
                    if (typeof response.mesg == 'object') {
                        for (megTxt in response.mesg) {
                            txt += response.mesg[megTxt] + '<br />';
                        }
                    }
                    else {
                        txt = response.mesg
                    }
                    //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                    if (response.code === 0) {
                        /* Alert the user that the server response*/
                        var sale_id = response.data.id;

                        jLib.message(txt, 'success');

                        //Reset the form
                        $('#cancel-btn').click();

                        //Initate print reciept
                        if($('#print_invoice').attr('checked')){
                            var action = $('#print-sale-receipt-url').val();
                            var url = action+'/'+sale_id;

                            window.open(url,action,"menubar=yes, width=600, height=500,location=no,status=no,scrollbars=yes,resizable=yes");
                        }
                    }
                    //* When there are Errors *//*
                    else if (response.code === 1) {
                        jLib.serverError(txt);
                    }

                    jLib.hideFormLoading();
                },
                error:function (xhr) {
                    console.log(xhr.responseText);
                    jLib.serverError();
                }
            });
        }
    }

};

/* when the page is loaded */
$(document).ready(function () {
    Sales.init();
});